﻿using C1.Win.C1Ribbon;
using CWCS.Entity;
using CWCS.UIDesigner.ConveryControl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace CWCS.UIControl.Convery
{
    public partial class FrmConveryDesigner : C1RibbonForm
    {
        DataTable dtSource = new DataTable();
        DataTable dtConfig = new DataTable("ConveryStations");
        BLL.ConveryBLL bll = new BLL.ConveryBLL();
        Dictionary<string, Color> listColor = new Dictionary<string, Color>();
        Dictionary<string, Point> Fulllocations = new Dictionary<string, Point>();
        Dictionary<ConveryStationInfo, ConveryStationsList> LstInfo = new Dictionary<ConveryStationInfo, ConveryStationsList>();
        Dictionary<ConveryUnit, DataRow> UnitsConfig = new Dictionary<ConveryUnit, DataRow>();
        List<DataRow> list = new List<DataRow>();
        public FrmConveryDesigner()
        {
            InitializeComponent();
        }

        private void FrmConveryDesigner_Load(object sender, EventArgs e)
        {
            LoadingData();
        }

        private void btnBatchInsert_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否要添加？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                FrmAddConvery frm = new FrmAddConvery();
                frm.ShowDialog();
                LoadingData();
            }
        }
        private void LoadingData()
        {
            dtSource = bll.GetWCS_OPCItem();
            if (File.Exists("ConveryStations.xml"))
            {
                try
                {
                    dtConfig.ReadXmlSchema("ConveryStations.xml");
                    dtConfig.ReadXml("ConveryStations.xml");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("加载配置文件失败，详细信息：" + ex.Message, "提示");
                    return;
                }
            }
            if (dtConfig.Columns.Count == 0)
            {
                dtConfig.Columns.Add("StationNo");//站台编号
                dtConfig.Columns.Add("StationType");//站台类型
                dtConfig.Columns.Add("locationx");//X
                dtConfig.Columns.Add("locationY");//Y
                dtConfig.Columns.Add("Width");//宽
                dtConfig.Columns.Add("Height");//高
                dtConfig.Columns.Add("Direction");//方向
                dtConfig.Columns.Add("DB");//DB块
                dtConfig.Columns.Add("Length");//DB块长度
                dtConfig.Columns.Add("Value");//DB值
                dtConfig.Columns.Add("IP");//IP地址
                dtConfig.Columns.Add("Belong");//所属线程
                dtConfig.Columns.Add("ZoneCode");//所属区域
            }
            InitConveryStations();
        }
        
        void InitConveryStations()
        {
            try
            {
                List<DataRow> drNew = new List<DataRow>();
                Color defaultcolor = new ConveryUnitRect().BackColor;
                listColor.Clear();
                listColor.Add("", defaultcolor);
                int count = 0;
                foreach (DataRow dr in dtSource.Select(" 1=1"))
                {
                    ConveryStationInfo csi = new ConveryStationInfo() { X = dr["locationx"].ToString(), Y = dr["locationy"].ToString(), Width = dr["width"].ToString(), Height = dr["height"].ToString(), ConveryNu = dr["itemname"].ToString() };
                    string converyStationNu = dr["stationno"].ToString();
                    if (LstInfo.FirstOrDefault(v => v.Key.Equals(csi)).Value == null)
                    {
                        count++;

                        DataRow[] drs = (dtConfig.Rows.Count > 0 ? dtConfig.Select("stationno='" + dr["stationno"] + "'") : dtSource.Select("1=2"));
                        ConveryUnitRect u;
                        if (drs.Count() > 0)
                        {
                            u = new ConveryUnitRect();
                            u.Visible = false;
                            u.XIndex = Convert.ToInt32(dr["locationx"]);
                            u.YIndex = Convert.ToInt32(dr["locationy"]);
                            u.WidthColumns = Convert.ToInt32(dr["width"]);
                            u.HeightRows = Convert.ToInt32(dr["height"]);

                            u.Data = dr;
                            if (dr["stationtype"].ToString().Trim() == "1")//入库申请站台
                                u.StationType = ConveryUnit.UnitType.InFeeding;
                            else if (dr["stationtype"].ToString().Trim() == "2")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.InFeeded;
                            else if (dr["stationtype"].ToString().Trim() == "3")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.OutFeeding;
                            else if (dr["stationtype"].ToString().Trim() == "2")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.OutFeeded;
                            else
                                u.StationType = ConveryUnit.UnitType.Normal;
                            if (dr["direction"].ToString().Trim() == "1")//输送机方向
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Vertical;
                            }
                            else if (dr["direction"].ToString().Trim() == "2")
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Horizontal;
                            }
                            else
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Empty;
                            }
                        }
                        else
                        {
                            u = new ConveryUnitRect();
                            u.Visible = true;
                            u.XIndex = Convert.ToInt32(dr["locationx"]);
                            u.YIndex = Convert.ToInt32(dr["locationy"]);
                            u.WidthColumns = Convert.ToInt32(dr["width"]);
                            u.HeightRows = Convert.ToInt32(dr["height"]);
                            u.Data = dr;
                            if (dr["stationtype"].ToString().Trim() == "1")//入库申请站台
                                u.StationType = ConveryUnit.UnitType.InFeeding;
                            else if (dr["stationtype"].ToString().Trim() == "2")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.InFeeded;
                            else if (dr["stationtype"].ToString().Trim() == "3")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.OutFeeding;
                            else if (dr["stationtype"].ToString().Trim() == "2")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.OutFeeded;
                            else
                                u.StationType = ConveryUnit.UnitType.Normal;
                            if (dr["direction"].ToString().Trim() == "2")//输送机方向
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Vertical;
                            }
                            else if (dr["direction"].ToString().Trim() == "1")
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Horizontal;
                            }
                            else
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Empty;
                            }
                            if (dr["arrowdirection"].ToString().Trim() == "0")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Empty;
                            if (dr["arrowdirection"].ToString().Trim() == "1")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Right;
                            if (dr["arrowdirection"].ToString().Trim() == "2")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Left;
                            if (dr["arrowdirection"].ToString().Trim() == "3")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Down;
                            if (dr["arrowdirection"].ToString().Trim() == "4")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Up;
                            if (dr["arrowdirection"].ToString().Trim() == "5")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Left_Right;
                            if (dr["arrowdirection"].ToString().Trim() == "6")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Up_Down;
                            if (dr["groupname"].ToString().Trim() == "Convery")
                                u.EquipmentType = ConveryUnit.UnitEquipmentType.Convery;
                            else if (dr["groupname"].ToString().Trim() == "PutRobot")
                                u.EquipmentType = ConveryUnit.UnitEquipmentType.PutRobot;
                            else if (dr["groupname"].ToString().Trim() == "PickRobot")
                                u.EquipmentType = ConveryUnit.UnitEquipmentType.PickRobot;
                            else
                                u.EquipmentType = ConveryUnit.UnitEquipmentType.Other;
                        }
                        string text = dr["itemname"].ToString();
                        u.ConveryNumber = text;


                        u.Text = csi.ToString();
                        if (!converyPanel1.Units.Exists(it => it.Data == u.Data))

                            converyPanel1.Add(u);


                        ConveryStationsList linfo = new ConveryStationsList();
                        linfo.unit = u;
                        linfo.lcd = csi;
                        LstInfo.Add(csi, linfo);
                        linfo.memo += "站台：" + text;
                        linfo.unit.BackColor = Color.FromArgb(166, 216, 255);
                        if (Convert.ToInt32(dr["itemid"].ToString()) == 2244 || Convert.ToInt32(dr["itemid"].ToString()) == 2245|| Convert.ToInt32(dr["itemid"].ToString()) == 2250 || Convert.ToInt32(dr["itemid"].ToString()) == 2251)
                        {
                            linfo.unit.BackColor = Color.FromArgb(68, 114, 196);
                        }
                        if (Convert.ToInt32(dr["itemid"].ToString()) == 2242 || Convert.ToInt32(dr["itemid"].ToString()) == 2243 || Convert.ToInt32(dr["itemid"].ToString()) == 2248 || Convert.ToInt32(dr["itemid"].ToString()) == 2249)
                            linfo.unit.BackColor = Color.FromArgb(165, 165, 165);
                        if (dr["itemname"].ToString().Contains("FXXX"))
                            linfo.unit.BackColor = Color.FromArgb(210, 105, 30);
                        if (dr["itemname"].ToString().Contains("SC"))
                            linfo.unit.BackColor = Color.FromArgb(255, 255, 0);
                        if (Convert.ToInt32(dr["itemid"].ToString())<=2000)
                            linfo.unit.BackColor = Color.FromArgb(112, 173, 71);
                        if (Convert.ToInt32(dr["stationtype"].ToString()) == 1)
                            linfo.unit.BackColor = Color.FromArgb(237, 125, 49);
                        if (dr["itemname"].ToString().Contains("提升机"))
                            linfo.unit.BackColor = Color.FromArgb(91, 155, 213);
                        ConveryStationsList linfo2 = LstInfo.FirstOrDefault(v => v.Key.Equals(csi)).Value;
                        linfo2.rows.Add(dr);
                        linfo2.total++;
                        LstInfo[csi].rows.Add(dr);
                    }
                    converyPanel1.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Source);
            }
        }

        struct ConveryStationInfo
        {
            public string X;
            public string Y;
            public string Width;
            public string Height;
            public string ConveryNu;

            public override bool Equals(object obj)
            {
                ConveryStationInfo csi = (ConveryStationInfo)obj;
                return csi.ConveryNu == this.ConveryNu;
            }
            public override string ToString()
            {
                return this.ConveryNu;
            }

        }

        class ConveryStationsList
        {
            public List<DataRow> rows = new List<DataRow>();
            public int total;
            public int fullConveryStations;
            public ConveryUnitRect unit;
            public string memo;
            public ConveryStationInfo lcd;
        }

        private void btnModity_Click(object sender, EventArgs e)
        {
            CWCS.Entity.WCS_OPCITEM item = new Entity.WCS_OPCITEM();

            item.Stationno = txtStationNum.Text;
            item.Stationtype = txtStationType.Text.Trim();
            item.Width = txtWidth.Text.Trim();
            item.Height = txtHight.Text.Trim();
            item.Locationx = txtLocationX.Text.Trim();
            item.Locationy = txtLocationY.Text.Trim();
            item.Direction = txtOrientation.Text.Trim();
            item.Signaltype = txtDB.Text.Trim();
            item.Value = txtLength.Text.Trim();
            item.Belong = txtBelong.Text.Trim();
            item.ArrowDirection = txtArrowDirection.Text.Trim();

            if (bll.UpdateOPCItem(item))
            {
                MessageBox.Show("更新成功！", "提示", MessageBoxButtons.OK);
                ConveryMove(item);

                var q = converyPanel1.Units.Where(v => ((DataRow)v.Data)["itemname"].ToString() == item.Stationno.Trim()).ToArray();
                if (q.Length == 1)
                {
                    foreach (ConveryUnit u in q)
                    {
                        u.XIndex = Convert.ToInt32(item.Locationx);
                        u.YIndex = Convert.ToInt32(item.Locationy);
                        u.Visible = true;
                    }
                }
            }
            //
            //  Right = 1,
            //Left = 2,
            //Down = 3,
            // Up = 4

            Thread thread = new Thread(new ThreadStart(SendInfo)); //生成监听线程；
            thread.IsBackground = false;//主线程关闭则辅线程自动关闭
            thread.Start();
        }
        public void SendInfo()
        {
            btnRefresh_Click(null, null);
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            var unitmove = converyPanel1.Units.Where(it => it.MoveFlag).ToArray();
            if (unitmove.Length > 0)
            {
                string move = "";
                foreach(ConveryUnit u in unitmove)
                {
                    move +="编号："+u.ConveryNumber+",";
                   
                   if(u.Data!=null)
                   {
                       WCS_OPCITEM item = new WCS_OPCITEM();
                       DataRow dr= (DataRow)(u.Data);
                       item.Stationno = dr["Stationno"].ToString().Trim();
                       item.Stationtype = dr["Stationtype"].ToString().Trim();
                       item.Width = dr["Width"].ToString().Trim();
                       item.Height = dr["Height"].ToString().Trim();
                       item.Locationx = u.XIndex.ToString();
                       item.Locationy = u.YIndex.ToString();
                       item.Direction = dr["Direction"].ToString().Trim();
                       item.Signaltype = dr["Signaltype"].ToString().Trim();
                       item.Value = dr["Value"].ToString().Trim();
                       item.Belong = dr["Belong"].ToString().Trim();
                       item.ArrowDirection = dr["ArrowDirection"].ToString().Trim();
                       if (bll.UpdateOPCItem(item))
                       {
                           //MessageBox.Show("更新成功！", "提示", MessageBoxButtons.OK);
                           move += "设备编号："+item.Stationno;
                           ConveryMove(item);
                           u.Visible = true;
                       }
                   }
                }
                if(!string.IsNullOrEmpty(move))
                  MessageBox.Show(move);
                converyPanel1.ClearMoveFlag();
            }
        }

        private void ConveryMove(WCS_OPCITEM entity)
        {
            var q = converyPanel1.Units.Where(v => ((DataRow)v.Data)["itemname"].ToString() == entity.Stationno.Trim()).ToArray();
            if (q.Length == 1)
            {
                foreach (ConveryUnit u in q)
                {
                    // u.XIndex = Convert.ToInt32(entity.Locationx);
                    //  u.YIndex = Convert.ToInt32(entity.Locationy);
                    u.Visible = false;
                }
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadingData();
        }

        private void converyPanel1_UnitMouseClick(object sender, MouseEventArgs e)
        {
            ConveryUnit u = (ConveryUnit)sender;
            if (u != null)
            {
                DataRow dr = (DataRow)u.Data;
                if (dr != null)
                {
                    txtStationNum.Text = dr["stationno"].ToString().Trim();
                    txtStationType.Text = dr["stationtype"].ToString().Trim();
                    txtWidth.Text = dr["width"].ToString().Trim();
                    txtHight.Text = dr["height"].ToString().Trim();
                    txtLocationX.Text = u.XIndex.ToString();

                    txtLocationY.Text = u.YIndex.ToString();
                    txtOrientation.Text = dr["DIRECTION"].ToString().Trim();
                    txtDB.Text = dr["signaltype"].ToString().Trim();
                    txtLength.Text = dr["value"].ToString().Trim();
                    txtBelong.Text = dr["Belong"].ToString().Trim();
                    txtArrowDirection.Text = dr["ArrowDirection"].ToString().Trim();
                    c1DockingTabPage1.TabVisible =true;
                    c1DockingTab3.SlideShowPage(c1DockingTabPage1);
                }
            }
        }

        private void btnCreateRoute_Click(object sender, EventArgs e)
        {
            FrmAddRoute frm = new FrmAddRoute();
            frm.ShowDialog();
        }
    }
}
